<template>
  <div class="sort_container">

      <div class="sortview__title">
      </div>
      <div class="sortable_dragable" v-loading="loading">
          <draggable
            v-model="datas"
            group="people"
            @start="onDragStart"
            @end="onDragEnd"
            :move="onDragItemMoved"
            item-key="id"
            v-bind="dragOptions"
            tag="transition-group"
          >
              <template #item="{element,index}">
                <div class="sort_container__item" >
                  <el-row justify="left" align="middle">
                      <el-avatar :size="50" :src="element.cover" shape="square"  v-if="showCover"></el-avatar>    
                      <p class="font_small ml-2">{{ index + 1 }} {{ element[getTitleProp] }}</p>                     
                  </el-row>
                    <el-popover placement="top" :width="220" trigger="click" popper-class="sort__pop">
                          <template #reference>
                                <el-button icon="el-icon-more" class="sort_item__more_btn mt-1" size="mini"></el-button>
                          </template>
                          <div class="sort__pop__inner">
                            <p class="mr-2">当前排序号 {{element.sort}}</p>
                            <el-button-group size="mini">
                              <el-button type="primary" icon="el-icon-top" title="置顶" @click="toTop(index)"></el-button>
                              <el-button type="primary" icon="el-icon-bottom" title="置底" @click="toBottom(index)"></el-button>
                            </el-button-group>
                          </div>
                    </el-popover>
                </div>
              </template>
          </draggable>
      </div>

  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from 'vuex'
import {
  locationApi
} from "@/manager-core/api/view/SortViewApi";

//https://github.com/SortableJS/vue.draggable.next
import draggable from "vuedraggable";



export default defineComponent({
  name: 'SortContainer',

  components: {
    draggable
  },

  props:{
    serverUrl:{
      type: String,
      required: false
    },
    titleProp:{
      type: String,
      required: false
    },
    autoInit:{
      type: Boolean,
      default: true,
      required: false
    },
    width:{
      type: String,
      default: "300",
      required: false
    },
    showCover:{
      type: Boolean,
      default: false,
      required: false
    },

  },

  data(){
    return {
      dataMap: {} as any, // 数据 map
      drag : true,
      datas : [] as any,
      loading : false,
      dragOptions: {
          animation: 200,
          group: "description",
          disabled: false,
          ghostClass: "ghost",
      }      
    }
  },

  methods:{
    init(){

    },

    // 初始化数据
    initData(){
      this.loading = true;
      locationApi(this.serverUrl, this.dataMap)
        .then((response) => {
          console.log("location resp : " , response)
          this.datas = response;
        })
        .catch((error) => {})
        .finally(() => {
          this.loading = false;
        });
    },

      // 外部筛选框输入
    updateParams(pkey: string, pval: object) {
      if (!this.dataMap) {
        this.dataMap = new Map();
      }

      this.dataMap.set(pkey, pval);
      // console.log("111", this.dataMap.set(pkey, pval));
      this.initData();
    },

    updateParamArys(pkeys: Array<string>, pvals: Array<object>) {
      if (!this.dataMap) {
        this.dataMap = new Map();
      }

      for (let i = 0; i < pkeys.length; i++) {
        this.dataMap.set(pkeys[i], pvals[i]);
      }

      // console.log("111", this.dataMap.set(pkey, pval));
      this.init();
    },

    onDragItemMoved(evt: any) {
      this.drag = true;
      this.loading = true;

      let start = evt.draggedContext.index;
      let startEle = evt.draggedContext.element;
      let end = evt.relatedContext.index;
      let endEle = evt.relatedContext.element;

      console.log("on drag item moved", "start : " + start + " - end : " + end);

      this.loading = false;
      return;

      // return false;

      //   被拖拽元素起始位置
      console.log(
        "start index: " + startEle.name + " -> end index : " + endEle.name
      );
      //   被拖拽元素终止位置
    },

    onDragStart(evt: any) {
      // console.log("onDragStart",this.datas)
      console.log("onDragStart", evt);
    },

    onDragEnd(evt: any) {      

      let oldIndex = evt.oldIndex;
      let newIndex = evt.newIndex;
      //...

      console.log("onDragEnd", evt);
      console.log("onDragEnd", oldIndex + " -> " + newIndex);
      

      this.onChangeEnd(oldIndex,newIndex);
    },

    // 置顶
    toTop(index:any){
      if(index == 0){
        return;
      }
      else {

        console.log("to top ",index)

        let data = this.datas[index];

        // 删除
        this.datas.splice(index,1);
        this.datas.unshift(data);

        this.onChangeEnd(index,0);

      }
    },

    // 置底
    toBottom(index:any){
      if(index == this.datas.length - 1){
        return;
      }
      else {

        let data = this.datas[index];

        // 删除
        this.datas.splice(index,1);


        this.datas.push(data);

        this.onChangeEnd(index,this.datas.length-1);
      }
    },

    onChangeEnd(oldIndex:Number,newIndex:Number){
      console.log("onChangeEnd",oldIndex,newIndex);

      //TODO  call api

    }





  },

  computed:{
    getTitleProp(){
      if (this.titleProp) {
        return this.titleProp;
      } else {
        return "title";
      }
    }
  },

  created(){
    if(this.autoInit){
      this.initData();
    }    
  },

  mounted(){
    console.log("muser")
  },

  setup(){
    // const store = useStore()

    // return {
    //   LoginByUsername:(userObj:any)=> store.dispatch('LoginByUsername')
    // }

  }


})



</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>

.appcontainer {
  overflow-x: scroll;
}
.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0s;
}

.list-group-item {
  cursor: move;
}
.list-group-item i {
  cursor: pointer;
}
</style>
